import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {TOKENURL} from "../../config/url.config";
import {Observable} from "rxjs/Observable";
import {Platform} from "ionic-angular";
import {Device} from "@ionic-native/device";

@Injectable()
export class LoginProvider {

    constructor(public http: HttpClient,
                private platform: Platform,
                private device: Device) {
    }

    doLogin(params: any): Observable<any> {
        let url = TOKENURL;
        let body = `grant_type=password&appkey=app&username=${params.UserName}&password=${params.Password}&client_id=msl&client_secret=123456&secretkey=111`;
        let headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        let deviceHeader = headers.set("device", this.getDeviceUUID());
        let options = {headers: deviceHeader};
        return this.http.post(url, body, options)
    }

    /**
     * 获取设备UUID
     * @returns {any}
     */
    private getDeviceUUID() {
        if (!this.platform.is('cordova')) {
            return "mobileweb";
        }
        else {
            return this.device.uuid || "";
        }
    }

    hasUnMessage() {
        let url = '/message/v1/app/hasUnReadMsg?notLoading=1';
        return this.http.get(url);
    }

    refreshToken() {
        if (localStorage.getItem('refresh_token')) {
            let url = TOKENURL;
            let token = localStorage.getItem('refresh_token');
            let body = `grant_type=refresh_token&appkey=app&refresh_token=${token}&client_id=msl&client_secret=123456&secretkey=111`;
            let headers = new HttpHeaders().set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            let deviceHeader = headers.set("device", this.getDeviceUUID());
            let options = {headers: deviceHeader};
            this.http.post(url, body, options).subscribe(result => {
                this.setLocalStorage(result);
            });
        }
    }

    setLocalStorage(res) {
        localStorage.setItem('hasSubordinate', res.hasSubordinate);
        localStorage.setItem('access_token', res.access_token);
        localStorage.setItem('refresh_token', res.refresh_token);
        localStorage.setItem('userName', res.userName);
        localStorage.setItem('roles', res.roles[0].authority);
        localStorage.setItem('nickName', res.nickName);
        localStorage.setItem('headImage', res.profileURL);
        localStorage.setItem('agentLevel', res.agentLevel);
    }

    /**
     * 从阿里云获取无痕验证随机码
     * @param data
     * @returns {Observable<any>}
     */
    validateCaptchaIndentation(data): Observable<any> {
        return this.http.get(`/aliyun/authentication?data=${data}`);
    }
}
